package com.aqie.medium.hash;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 535 hash 加密解密
 * todo
 */
public class TinyURL {
    Map<String, String> map = new HashMap<>();
    int max = 'Z';
    Random r = new Random(max);

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        int i = 0;
        String key = "";
        while (i < 5){
            key += (char)(r.nextInt(max));
            i++;
        }

        while (map.get(key) != null){
            key += r.nextInt();
        }

        map.put(key, longUrl);
        return "http://" + key;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return map.get(shortUrl.substring(7));
    }
}
